package org.jeecg.modules.monitoring.j_monitoring.controller;

import java.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.monitoring.j_monitoring.utils.EquipmentUtils;
import org.jeecg.modules.monitoring.j_monitoring.entity.MGlComputingResource;
import org.jeecg.modules.monitoring.j_monitoring.mapper.MGlComputingResourceMapper;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlComputingResourceService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.monitoring.j_monitoring.service.IMGlResourceStorageService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlVirtualizationClusterService;
import org.jeecg.modules.monitoring.j_monitoring.service.impl.GatewaySystemFdnServiceImpl;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 计算资源
 * @Author: xiaoyq
 * @Date:   2023-01-08
 * @Version: V1.0
 */
@Api(tags="计算资源")
@RestController
@RequestMapping("/j_monitoring/mGlComputingResource")
@Slf4j
public class MGlComputingResourceController extends JeecgController<MGlComputingResource, IMGlComputingResourceService> {
	@Resource
	private MGlComputingResourceMapper mGlComputingResourceMapper;

	@Autowired
	private IMGlResourceStorageService glResourceStorageService;
	 @Resource
	 private GatewaySystemFdnServiceImpl systemFdnService;
	/**
	 * 分页列表查询
	 *
	 * @param mGlComputingResource
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "计算资源-分页列表查询")
	@RequiresPermissions("计算资源:查询")
	@ApiOperation(value="计算资源-分页列表查询", notes="计算资源-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MGlComputingResource mGlComputingResource,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Result<Page<MGlComputingResource>> result=new Result<>();
		Page<MGlComputingResource> pagelist = new Page(pageNo, pageSize);
		QueryWrapper<MGlComputingResource> queryWrapper = QueryGenerator.initQueryWrapper(mGlComputingResource, req.getParameterMap());
		pagelist=mGlComputingResourceMapper.getPageList(pagelist,queryWrapper);
		List<MGlComputingResource> networkResourceList  = pagelist.getRecords();
		List<String> ipList = new ArrayList<>();
		for (MGlComputingResource computingResource : networkResourceList){
			if (!computingResource.getIsMonitor()){
				computingResource.setMonitorStatus(EquipmentUtils.getMonitorStatus(computingResource.getWhetherToMonitor()));
			}
			ipList.add(computingResource.getDeviceIp());
		}

		if (mGlComputingResource.getIsMonitor()){
			//查看ping返回值
			Map<String,Object> map = systemFdnService.getPingMonitor(ipList);
			for (MGlComputingResource computingResource : networkResourceList){
				computingResource.setMonitorStatus(map.get(computingResource.getDeviceIp()).toString());
			}
		}

		result.setCode(200);
		result.setSuccess(true);
		result.setResult(pagelist);
		return result;
	}

	 /**
	  * 设备地图查询
	  */
	 //@AutoLog(value = "计算资源-设备地图查询")
	 @RequiresPermissions("计算资源:查询")
	 @ApiOperation(value="计算资源-设备地图查询", notes="计算资源-设备地图查询")
	 @GetMapping(value = "/getDeviceMap")
	 public Result<?> getDeviceMap(
			 @RequestParam(name="id",required=true) String id,
			 HttpServletRequest req) {
		 MGlComputingResource entity = this.service.getById(id);
		 JSONArray nodes = new JSONArray();
		 JSONArray edges = new JSONArray();
		 JSONObject result=new JSONObject();
		 result.put("nodes",nodes);
		 result.put("edges",edges);
		 if(entity==null){
			 return Result.OK(result);
		 }
		 //主要有两个数据，一个是nodes，一个是edges
		 /**
		  * node
		  * 	  id: "0",
		  *       name: "Myriel",
		  *       symbolSize: 19.12381,
		  *       x: -53.365552,
		  *       y: 59.93808,
		  *       value: 28.685715,
		  *       category: 0
		  */

		 /**
		  * edge
		  * 	  id: null,
		  *       source: "35",
		  *       target: "34"
		  */


		 if(entity.getClusterId()!=null && !"".equals(entity.getClusterId())){
			 IMGlVirtualizationClusterService clusterService = ApplicationContextUtil.getContext().getBean(IMGlVirtualizationClusterService.class);
			 JSONObject root = clusterService.getDeviceMapById(nodes,edges,0,0,entity.getClusterId());
		 }
		 else {
			 JSONObject root = this.service.getDeviceMapById(nodes,edges,0,0,entity.getId());
		 }

		 return Result.OK(result);
	 }

	 /**
	  * 设备地图查询
	  */
	 //@AutoLog(value = "计算资源-设备地图查询")
	 @RequiresPermissions("计算资源:查询")
	 @ApiOperation(value="计算资源-设备地图查询", notes="计算资源-设备地图查询")
	 @GetMapping(value = "/getDeviceTree")
	 public Result<?> getDeviceTree(
			 @RequestParam(name="id",required=true) String id,
			 HttpServletRequest req) {
		 JSONObject result=new JSONObject();
		 MGlComputingResource entity = this.service.getById(id);
		 if(entity==null){
			 return Result.error("设备不存在");
		 }

		 if(entity.getClusterId()!=null && !"".equals(entity.getClusterId())){
			 IMGlVirtualizationClusterService clusterService = ApplicationContextUtil.getContext().getBean(IMGlVirtualizationClusterService.class);
			 JSONObject root = clusterService.getDeviceTreeById(entity.getClusterId());
			 return Result.OK(root);
		 }
		 else {
			 JSONObject root = this.service.getDeviceTreeById(entity.getId());
			 return Result.OK(root);
		 }
	 }

	/**
	 *   添加
	 *
	 * @param mGlComputingResource
	 * @return
	 */
	@AutoLog(value = "计算资源-添加")
	@ApiOperation(value="计算资源-添加", notes="计算资源-添加")
	@RequiresPermissions("计算资源:添加")
	@PostMapping(value = "/add")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> add(@RequestBody MGlComputingResource mGlComputingResource) {
		String associatedStorageId = mGlComputingResource.getAssociatedStorageId();
		//mGlComputingResource.setAssociatedStorageId("");

		MGlComputingResource m = new MGlComputingResource();
		QueryWrapper<MGlComputingResource> queryWrapper = QueryGenerator.initQueryWrapper(m,new HashMap<>());
		queryWrapper.eq("equipment_no",mGlComputingResource.getEquipmentNo());
		if (mGlComputingResourceMapper.selectCount(queryWrapper)>0){
			return Result.error("设备编号重复，添加失败！");
		}

		mGlComputingResource.autoSetDisplayName();
		this.service.save(mGlComputingResource);
		this.glResourceStorageService.batchDealData("JS",mGlComputingResource.getId(),associatedStorageId);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param mGlComputingResource
	 * @return
	 */
	@AutoLog(value = "计算资源-编辑")
	@ApiOperation(value="计算资源-编辑", notes="计算资源-编辑")
	@RequiresPermissions("计算资源:编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	@Transactional(rollbackFor = Exception.class)
	public Result<String> edit(@RequestBody MGlComputingResource mGlComputingResource) {
		String associatedStorageId = mGlComputingResource.getAssociatedStorageId();
		//mGlComputingResource.setAssociatedStorageId("");
		mGlComputingResource.autoSetDisplayName();
		this.service.updateById(mGlComputingResource);
		this.glResourceStorageService.batchDealData("JS",mGlComputingResource.getId(),associatedStorageId);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "计算资源-通过id删除")
	@ApiOperation(value="计算资源-通过id删除", notes="计算资源-通过id删除")
	@RequiresPermissions("计算资源:删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		this.glResourceStorageService.batchRemoveStorage("JS",id);
		this.service.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "计算资源-批量删除")
	@ApiOperation(value="计算资源-批量删除", notes="计算资源-批量删除")
	@RequiresPermissions("计算资源:批量删除")
	@DeleteMapping(value = "/deleteBatch")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		this.glResourceStorageService.batchRemoveStorageByResIds("JS",idList);
		this.service.removeByIds(idList);
		return Result.OK("批量删除成功!");
	}

	 /**
	  *  监控
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "计算资源-添加监控")
	 @ApiOperation(value="计算资源-添加监控", notes="计算资源-添加监控")
	 @RequiresPermissions("计算资源:监控")
	 @RequestMapping(value = "/monitor", method = {RequestMethod.POST})
	 @Transactional(rollbackFor = Exception.class)
	 public Result<String> monitor(@RequestParam(name="ids",required=true) String ids) {
		 List<String> idList = Arrays.asList(ids.split(","));
		 if(idList.size()==0){
			 return Result.error("数据为空!");
		 }
		 UpdateWrapper<MGlComputingResource> updateWrapper = new UpdateWrapper<>();
		 LambdaUpdateWrapper<MGlComputingResource> lambdaUpdateWrapper = updateWrapper.lambda();
		 idList.forEach(item->lambdaUpdateWrapper.or(qr->qr.eq(MGlComputingResource::getId,item)));
		 lambdaUpdateWrapper.set(MGlComputingResource::getWhetherToMonitor,"1");
		 this.service.update(updateWrapper);
		 return Result.OK("监控添加成功!");
	 }

	 /**
	  *  取消监控
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "计算资源-取消监控")
	 @ApiOperation(value="计算资源-取消监控", notes="计算资源-取消监控")
	 @RequiresPermissions("计算资源:取消监控")
	 @RequestMapping(value = "/unmonitor", method = {RequestMethod.POST})
	 @Transactional(rollbackFor = Exception.class)
	 public Result<String> unmonitor(@RequestParam(name="ids",required=true) String ids) {
		 List<String> idList = Arrays.asList(ids.split(","));
		 if(idList.size()==0){
			 return Result.error("数据为空!");
		 }
		 UpdateWrapper<MGlComputingResource> updateWrapper = new UpdateWrapper<>();
		 LambdaUpdateWrapper<MGlComputingResource> lambdaUpdateWrapper = updateWrapper.lambda();
		 idList.forEach(item->lambdaUpdateWrapper.or(qr->qr.eq(MGlComputingResource::getId,item)));
		 lambdaUpdateWrapper.set(MGlComputingResource::getWhetherToMonitor,"0");
		 this.service.update(updateWrapper);
		 return Result.OK("监控取消成功!");
	 }


	 /**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@RequiresPermissions("计算资源:查询")
	@ApiOperation(value="计算资源-通过id查询", notes="计算资源-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MGlComputingResource> queryById(@RequestParam(name="id",required=true) String id) {
		MGlComputingResource mGlComputingResource = this.service.getById(id);
		if(mGlComputingResource==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mGlComputingResource);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param mGlComputingResource
    */
	@RequiresPermissions("计算资源:导出")
    @RequestMapping(value = "/exportXls", method = RequestMethod.GET)
	@ApiOperation(value="计算资源-导出", notes="计算资源-导出")
    public ModelAndView exportXls(HttpServletRequest request, MGlComputingResource mGlComputingResource) {
        return super.exportXls(request, mGlComputingResource, MGlComputingResource.class, "计算资源");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
	@RequiresPermissions("计算资源:导入")
	@ApiOperation(value="计算资源-导入", notes="计算资源-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MGlComputingResource.class);
    }


	 @RequestMapping(value = "/testImport", method = RequestMethod.POST)
	 public void testImport(HttpServletRequest request, HttpServletResponse response) {
		this.service.testImport(request);
	 }

	 @Override
	 protected  void beforeImportExcel(List<MGlComputingResource> list){
		 list.forEach(item->{
		 	if(org.apache.commons.lang.StringUtils.isNotEmpty(item.getCabinet())){
				item.setCabinet(item.getCabinet().trim());
			}
			if(org.apache.commons.lang.StringUtils.isNotEmpty(item.getMachineRoom())){
			   item.setMachineRoom(item.getMachineRoom().trim());
			}
			 if(org.apache.commons.lang.StringUtils.isNotEmpty(item.getPersonLiable())){
				 item.setPersonLiable(item.getPersonLiable().trim());
			 }
		 });
	 }

	 @Override
	 protected void afterImportExcel(List<MGlComputingResource> list){
		 UpdateWrapper<MGlComputingResource> updateWrapper = new UpdateWrapper<>();
		 updateWrapper.lambda().isNull(MGlComputingResource::getCabinetId);
		 updateWrapper.setSql("Cabinet_id=(select id from m_cabinet where Cabinet=name LIMIT 1)");
		 this.service.update(updateWrapper);

		 updateWrapper.clear();
		 updateWrapper.lambda().isNull(MGlComputingResource::getClusterId);
		 updateWrapper.setSql("Cluster_id=(select id from m_gl_virtualization_cluster where Cluster=name LIMIT 1)");
		 this.service.update(updateWrapper);

		 updateWrapper.clear();
		 updateWrapper.lambda().isNull(MGlComputingResource::getMachineRoomId);
		 updateWrapper.setSql("Machine_Room_Id=(select id from m_machine_room where machine_room=name LIMIT 1)");
		 this.service.update(updateWrapper);

		 updateWrapper.clear();
		 updateWrapper.lambda().isNull(MGlComputingResource::getPersonLiableId);
		 updateWrapper.setSql("person_liable_id=(select id from sys_user where person_liable=realname LIMIT 1)");
		 this.service.update(updateWrapper);
	 }

}
